import { Effect, ImmerReducer,history } from 'umi'
import { login } from '@/service/admin'
import { message } from 'antd'
import { setItem, getItem } from '@/utils/cookie'
export interface ILoginState {
  adminname: string
  token: string
  role: string
}
export interface ILoginModelInterface {
  namespace: 'admin'
  state: ILoginState
  effects: {
    loginreq: Effect
  }
  reducers: {
    changeAdminName: ImmerReducer<ILoginState>,
    changeToken: ImmerReducer<ILoginState>,
    changeRole: ImmerReducer<ILoginState>
  }
}
const LoginModel: ILoginModelInterface = {
  namespace: "admin", //命名空间---区分模块
  state: {
    adminname: getItem('adminname') || '',
    token: getItem('token') || '',
    role: getItem('role') || "1"
  },
  effects: {//就是vuex中的actions 必须写成generator的写法
    *loginReq({ payload }: any, { call, put }: any): any {
      // 异步操作数据
      const res = yield call(login, payload)
      console.log(res);
      if (res.data.code === "10003") {
        message.error('账户名或密码错误！')
      } else if (res.data.code === '10005') {
        message.error('没有此账号，请与管理员联系')
      } else {
        yield put({
          type: 'changeAdminName', payload: res.data.data.adminname
        })
        yield put({
          type: 'changeToken', payload: res.data.data.token
        })
        yield put({
          type: 'changeRole', payload: res.data.data.role
        })
        // 保存数据到本地
        setItem('adminname', res.data.data.adminname, 7)
        setItem('token', res.data.data.token, 7)
        setItem('role', res.data.data.role, 7)

        // 跳转到系统首页
        history.push('/home')
      }


    }
  },
  reducers: {//类似于vuex中的mutations
    changeAdminName(state: ILoginState, action: any) {
      state.adminname = action.payload
    },
    changeToken(state: ILoginState, action: any) {
      state.token = action.payload
    },
    changeRole(state: ILoginState, action: any) {
      state.role = action.payload
    }
  }
}

export default LoginModel